package controllers

import (
	"github.com/revel/revel"
	"strconv"
	"wuhuaguo.com/whg01/app/models"
	"wuhuaguo.com/whg01/app/routes"
)

type Sellers struct {
	Application
}

func (c Sellers) Index() revel.Result {
	return c.Redirect(routes.Application.Index())
}

/*
	获取所有商户信息
*/
func (c Sellers) GetALLMerchant() revel.Result {
	return c.RenderJson(models.GetALLMerchant())
}

func (c Sellers) Approve(mcId string) revel.Result {
	id, err := strconv.Atoi(mcId)
	if err != nil {
		return c.RenderError(err)
	}
	models.UpdateMCStatus(id, 1)
	return c.RenderText("OK")
}

//http://127.0.0.1:9090/create_mc?
//yyz-tel=1&
//mcname=3&
//mc_addr=2&
//main-p=3&
//kf-tel=3&submit=req

func (c Sellers) CreateMerchant() revel.Result {
	f := true
	user := c.RenderArgs["user"].(*models.User)
	if c.Params.Get("submit") == "req" {
		f = false
		// 创建一个商户信息，未审核的
		mc_name := c.Params.Get("mcname")
		mc_kf := c.Params.Get("kf-tel")
		mc_addr := c.Params.Get("mc_addr")
		mc_p := c.Params.Get("main-p")

		merchant := &models.MerChant{
			Name:         mc_name,
			Administor:   user.UserId,
			Tel:          mc_kf,
			Addr:         mc_addr,
			MainProducts: mc_p,
			Status:       -1,
		}
		//添加到数据库中
		//需要进行事物处理
		rawrole := user.Role
		txn, err := models.Dbm.Begin()
		text := ""
		if err != nil {
			revel.ERROR.Println(err.Error())
			text = "提交申请失败，请联系管理员"
		} else {
			//插入数据库
			err := txn.Insert(merchant)
			if err != nil {
				revel.ERROR.Println(err.Error())
				text = "提交申请失败！请联联系管理员"
			} else {
				//更新用户信息
				models.UpdateUserRole(user.UseridStr(), 1, txn)
				text = "申请已提交，请耐心等待审核"
			}
		}
		if err = txn.Commit(); err != nil {
			revel.ERROR.Printf("grop commit error %s", err.Error())
			txn.Rollback()
			user.Role = rawrole
		}

		models.AddMc(merchant)
		return c.Render(user, f, text)
	} else {
		return c.Render(user, f)
	}
}
